package com.labs;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 创建文件
 */
public class CreateFiles {
    public static void createFilesWithThreads(String filePath, int totalFiles, int threadCount) throws  InterruptedException{
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger errorCount = new AtomicInteger(0);
        System.out.println("使用 " + threadCount + " 个线程创建 " + totalFiles + " 个文件");
        int filesPerThread = totalFiles / threadCount;
        int remainingFiles = totalFiles % threadCount;

        for (int i = 0; i < threadCount; i++) {
            int startIndex = i * filesPerThread;
            int endIndex = startIndex + filesPerThread;

            if(i == threadCount -1){
                endIndex += remainingFiles;
            }

            final int threadId = i;
            final int finalStart = startIndex;
            final int finalEnd = endIndex;
            executor.submit(() -> {
                System.out.println("线程 " + threadId + " 开始创建文件，范围: " + finalStart + " - " + (finalEnd - 1));
                int threadSuccess = 0;
                int threadError = 0 ;

                for (int j = finalStart; j < finalEnd; j++) {
                    try{
                        String fileName = String.format("SOP-01-%05d.txt", j);
                        File targetFile = new File(filePath+File.separator+fileName);
                        if(!targetFile.exists()) {
                            targetFile.createNewFile();
                            try (FileWriter writer = new FileWriter(targetFile, true)) {
                                writer.write("文件名是: " + fileName);
                            }
                            threadSuccess++;
                        }else{
                            System.out.println("文件已存在..."+fileName);
                        }
                    }catch(IOException e){
                        System.err.println("线程 " + threadId + " 创建文件失败: " + e.getMessage());
                        threadError++;
                    }
                }
                successCount.addAndGet(threadSuccess);
                errorCount.addAndGet(threadError);
                System.out.println("线程 " + threadId + " 完成: 成功 " + threadSuccess + " 个, 失败 " + threadError + " 个");
            });
        }
        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        boolean finished = executor.awaitTermination(10, TimeUnit.MINUTES);

        if (finished) {
            System.out.println("文件创建完成!");
            System.out.println("成功创建: " + successCount.get() + " 个文件");
            System.out.println("创建失败: " + errorCount.get() + " 个文件");
        } else {
            System.out.println("任务超时，强制关闭线程池");
            executor.shutdownNow();
        }
    }
}
